package com.soup.lab.spring.web.tools.enums.validation;

import com.soup.lab.spring.web.tools.enums.basic.CodeEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolationException;
import java.util.Objects;

/**
 * 枚举项编码校验器
 * 被注释的对象，必须在枚举中可以找到对应的键 {@link Objects#equals(Object, Object)}
 *
 * 当被修饰值为 null 时，不进行校验并返回 true。如果需要进行非空约束，请附加使用 @NonNull
 *
 * @author Soup
 */
public class EnumCodeConstraintValidator implements ConstraintValidator<EnumCode, Object> {

    private Class<? extends Enum<?>> type;

    @Override
    public void initialize(EnumCode constraintAnnotation) {
        type = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(value == null) {
            return true;
        }
        if(CodeEnum.class.isAssignableFrom(type)) {
            return CodeEnum.containsGeneric(value, type);
        }
        return false;
    }

}
